package com.kevin.mapping.script.lexer;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kevin.mapping.script.engine.JSONEnv;

import java.math.BigDecimal;

public class PathValue extends Token {

    private final Path[] paths;
    public int offset;     // relative address

    public PathValue(int type, String s) {
        super(type);
        paths = Path.parser(s);
    }

    @Override
    public Object getValue(JSONEnv env) {
        Object data = env.getData();
        for (Path path : paths) {
            if (null == data) {
                return null;
            }
            if (data instanceof JSONObject) {
                data = ((JSONObject) data).get(path.getPath());
            } else if (data instanceof JSONArray) {
                if (path.getStartIndex() != null) {
                    data = ((JSONArray) data).get(path.getStartIndex());
                }
            }
        }
        return data;
    }

    public String toString() {
        StringBuilder ret = new StringBuilder();

        for (Path path : paths) {
            if (ret.length() > 0) {
                ret.append(path.toString());
            }
        }
        return ret.toString();
    }

    public Path[] getPaths() {
        return paths;
    }

    public int getOffset() {
        return offset;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }


    @Override
    public Integer getIntValue(JSONEnv env) {
        Object v = getValue(env);
        if (v instanceof Integer) {
            return Integer.valueOf(v.toString());
        }
        return null;
    }

    @Override
    public Long getLongValue(JSONEnv env) {
        Object v = getValue(env);
        if (v instanceof Long) {
            return Long.valueOf(v.toString());
        }
        return null;
    }

    @Override
    public Double getDoubleValue(JSONEnv env) {
        Object v = getValue(env);
        if (v instanceof Long) {
            return Double.valueOf(v.toString());
        }
        return null;
    }

    @Override
    public BigDecimal getBigDecimalValue(JSONEnv env) {
        Object v = getValue(env);
        try {
            return new BigDecimal(v.toString());
        } catch (Exception e) {
            return null;
        }

    }

    @Override
    public String getStrValue(JSONEnv env) {
        Object v = getValue(env);
        return String.valueOf(v);
    }

    @Override
    public Object getObjectValue(JSONEnv env) {
        return getValue(env);
    }
}
